package com.andy.nature.view

import android.R
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import kotlin.math.cos
import kotlin.math.sin


/**
 * @author Andy
 * @date 2024/2/4
 * @description HighLightView
 */

class HighLightView : View {
    private lateinit var bms: Bitmap //source 原图
    private lateinit var bmm: Bitmap //mask 蒙版
    private lateinit var paint: Paint
    private val mWidth = 4
    private val step = 15
    private var index = -1
    private var max = 100
    private var colors = IntArray(max)
    private val highlightColors = intArrayOf(-0x100000, 0, -0x66de, 0, -0xff0100, 0)


    constructor(context: Context) : super(context) {
        TabView(context, null)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initView(context, attrs)
    }

    private fun initView(context: Context, attrs: AttributeSet?) {
        bms = decodeBitmap(R.drawable.btn_star_big_off)
        bmm = Bitmap.createBitmap(bms.width, bms.height, Bitmap.Config.ALPHA_8)
        val canvas = Canvas(bmm)
        canvas.drawBitmap(bms, 0f, 0f, null)
        paint = Paint(Paint.ANTI_ALIAS_FLAG)
    }

    private fun decodeBitmap(resId: Int): Bitmap {
        val options = BitmapFactory.Options()
        options.inMutable = true
        return BitmapFactory.decodeResource(resources, resId, options)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        // draw blur shadow
        var i = 0
        while (i < 360) {
            val x = mWidth * cos(Math.toRadians(i.toDouble())).toFloat()
            val y = mWidth * sin(Math.toRadians(i.toDouble())).toFloat()
            canvas.drawBitmap(bmm, x, y, paint)
            i += step
        }
        canvas.drawBitmap(bms, 0f, 0f, null)
        if (index == -1) {
            return
        }
        index++
        if (index > max + 1) {
            return
        }
        if (index >= max) {
            paint.color = Color.TRANSPARENT
        } else {
            paint.color = colors[index]
        }
        postInvalidateDelayed(200)
    }

    fun shake() {
        index = 0
        var i = 0
        while (i < max) {
            colors[i] = highlightColors[i % highlightColors.size]
            i += 2
        }
        postInvalidate()
    }
}

